package com.hyj.util;



import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;

import com.hyj.jpdy.bean.vo.HttpBean;



public class HttpUtil {

	private static Logger logger = Logger.getLogger(HttpUtil.class);
	
	public static HttpBean httpResp(String url,String param,String charset,String method) throws IOException{
		HttpBean vo  = new HttpBean();
		if(charset == null||"".equals(charset)){  
        	charset = "UTF-8";
        }
        if(method == null||"".equals(method)){  
        	method = "POST";
        }
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod(method);
		connection.setConnectTimeout(10000);
		connection.setRequestProperty("Accept", "text/xml");
	 
		connection.getOutputStream().write(param.getBytes());//会隐式调用 connect
		connection.getOutputStream().flush();
		connection.getOutputStream().close();
		
		
		//http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
		// 取得输入流，并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), charset));// 设置编码,否则中文乱码
		
		String lines = "";
		StringBuffer reuslts = new StringBuffer();
		while ((lines = reader.readLine()) != null) {
			reuslts.append(lines);
		}
		reader.close();
		Map<String,List<String>> map = connection.getHeaderFields();
		Set<String> keys = map.keySet();
		Map<String,String> cookieMap = new HashMap<String,String>();
		for(String key: keys){
			if("Set-Cookie".equals(key)){
				List<String> list = map.get(key);
				for(String value:list){
					String cookie =  value.substring(0,value.indexOf(";"));
					System.out.println(key+" ----->>> "+cookie+" ::: "+value);
				    String cookieKey = cookie.substring(0,cookie.indexOf('='));
				    String cookieValue = cookie.substring(cookie.indexOf('=')+1);
				    System.out.println(cookieKey+" --- "+cookieValue);
				    cookieMap.put(cookieKey, cookieValue);
				}
				break;
			}
		}
		vo.setCookie(cookieMap);
		try {
			/**
			 * <result>999</result>
				  <description>系统繁忙，请稍候重试</description>
				  <ssoid></ssoid>
				  <userNumber></userNumber>
				  <svrInfoURL>http://smsrebuild1.mail.10086.cn/disk/disk/v?</svrInfoURL>
				  <logoutURL>http://mail.10086.cn/Login/VirtualDiskLogOut.ashx</logoutURL>
				</return>
			 * 
			 */
			Document doc = DocumentHelper.parseText(reuslts.toString());
			String userNumber = doc.selectSingleNode("//userNumber").getText();
			String result = doc.selectSingleNode("//result").getText();
			String description = doc.selectSingleNode("//description").getText();
			String ssoid = doc.selectSingleNode("//ssoid").getText();
			vo.setSid(ssoid);
			vo.setUserNumber(userNumber);
			vo.setDesc(description);
			vo.setReturnCode(result);
			
		} catch (DocumentException e) {
			 throw new IOException(e);
		}
		
		
		vo.setRespContent(reuslts.toString());
		return vo;
	}
	
	
	public static String  getRemoteResp(String url,String param,String charset,String method) throws IOException{
        
        if(charset == null||"".equals(charset)){  
        	charset = "UTF-8";
        }
        if(method == null||"".equals(method)){  
        	method = "POST";
        }
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod(method);
		connection.setRequestProperty("Content-type", "text/xml");
		connection.setConnectTimeout(10000);
		connection.setRequestProperty("Accept", "text/xml");
	 
		connection.getOutputStream().write(param.getBytes());//会隐式调用 connect
		connection.getOutputStream().flush();
		connection.getOutputStream().close();
		
		//http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
		// 取得输入流，并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), charset));// 设置编码,否则中文乱码
		
		String lines = "";
		StringBuffer reuslts = new StringBuffer();
		while ((lines = reader.readLine()) != null) {
			reuslts.append(lines);
		}
		reader.close();
		return reuslts.toString();
	}
	
	/**
	 * 不需要 发送数据到服务器，直接获取东西
	 * */
	public static String  getRemoteResp(String url,String charset) throws IOException{
        
        if(charset == null||"".equals(charset)){  
        	charset = "UTF-8";
        }
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setDoOutput(false);
		connection.setDoInput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0");
		connection.setConnectTimeout(5000);
		int rescode = connection.getResponseCode();
		System.out.println("-----响应编码 :"+rescode);
	 
		
		//http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
		// 取得输入流，并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), charset));// 设置编码,否则中文乱码
		
		String lines = "";
		StringBuffer reuslts = new StringBuffer();
		while ((lines = reader.readLine()) != null) {
			reuslts.append(lines);
		}
		reader.close();
		return reuslts.toString();
	}
	
	public static String  getRemoteResp(String url,String param,String charset) throws IOException{
         
        if(charset == null||"".equals(charset)){  
        	charset = "UTF-8";
        }
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Content-type", "text/xml");
		connection.setConnectTimeout(10000);
		connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0");
	 
		connection.getOutputStream().write(param.getBytes());//会隐式调用 connect
		connection.getOutputStream().flush();
		connection.getOutputStream().close();
		
		//http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
		// 取得输入流，并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), charset));// 设置编码,否则中文乱码
		
		String lines = "";
		StringBuffer reuslts = new StringBuffer();
		while ((lines = reader.readLine()) != null) {
			reuslts.append(lines);
		}
		reader.close();
		return reuslts.toString();
	}
	
	public static byte[] getBytes(String url) throws IOException{
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Content-type", "text/xml");
		connection.setConnectTimeout(5000);
		connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0");
		connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		
		
		// 取得输入流，并使用Reader读取
		InputStream is = connection.getInputStream();
		
		 
		byte[] temp  = new byte[1024];;
		int length = 0;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((length =is.read(temp))>0) {
			outStream.write(temp, 0, length);
		}
		is.close();
		return outStream.toByteArray() ;
	} 
	
	
	
	/**
	 * 写入cookie
	 */
	public static String  getRemoteResp2(String url,String param,String charset,Map<String,String> cookies) throws IOException{
        
        if(charset == null||"".equals(charset)){  
        	charset = "UTF-8";
        }
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-type", "text/xml");
		connection.setConnectTimeout(10000);
		connection.setRequestProperty("Accept", "text/xml");
	 
		//写入cookie
		Set<Map.Entry<String, String>>  sets = cookies.entrySet();
		StringBuffer cookie = new StringBuffer();
		for(Map.Entry<String, String> item:sets ){
			cookie.append(item.getKey()+"="+item.getValue()+";");
	     
		//Cookie: WT_FPC=id=2ca5ebbeacac89aea6e1362477642620:lv=1363413284911:ss=1363413276505; Login_UserNumber=18320805248;
		}
		connection.setRequestProperty("Cookie", cookie.toString());
		
		connection.getOutputStream().write(param.getBytes());//会隐式调用 connect
		connection.getOutputStream().flush();
		connection.getOutputStream().close();
		
		int rescode = connection.getResponseCode();
		System.out.println("-----响应编码 :"+rescode);
		if(rescode!= HttpURLConnection.HTTP_OK){
			return "";
		}
		
		//http请求实际上直到HttpURLConnection的getInputStream()这个函数里面才正式发送出去。
		// 取得输入流，并使用Reader读取
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				connection.getInputStream(), charset));// 设置编码,否则中文乱码
		
		String lines = "";
		StringBuffer reuslts = new StringBuffer();
		while ((lines = reader.readLine()) != null) {
			reuslts.append(lines);
		}
		reader.close();
		return reuslts.toString();
	}
	
	
	public static Map<?,?> ParserRequest(HttpServletRequest request){
		
		try {
			BufferedReader read = request.getReader();

			String ss = null;
			StringBuffer sbf = new StringBuffer();
			while ((ss = read.readLine()) != null) {
				sbf.append(ss);
			}
			String reqparam = sbf.toString();
			logger.info("请求参数" + reqparam);
			Map<?, ?> m = (Map<?, ?>) JsonUtil.fromJson(reqparam, Map.class);
			return m;
		} catch (Exception e) {
			logger.error("参数不对", e);
			return new HashMap<String, Object>();
		}
	}
	
	public static OutputStream writeResponse(HttpServletRequest request,
			      HttpServletResponse response) throws IOException{
		OutputStream out = null;
		String encoding = request.getHeader("Accept-Encoding");
		if (encoding != null && encoding.indexOf("gzip") != -1) {
			response.setHeader("Content-Encoding", "gzip");
			out = GzipUtil.getGzipOutputStream(response.getOutputStream());
		} else {
			out = response.getOutputStream();
		}
		return out;
	}
	
	public static void main(String[] args) throws IOException, URISyntaxException{
		String url = "http://www.sina.com.cn/";
	 
		String ss =  new String(getBytes(url),"gbk");
		System.out.println( " --> "+ss);
	}
}
